//
//  SIBaseViewController.swift
//  SinaImiate
//
//  Created by xiaoming on 16/6/29.
//  Copyright © 2016年 GoodJob. All rights reserved.
//

import UIKit

class SIBaseViewController: UIViewController {
    
    var visitorInfoDictonary: [String: String]?
    
    var isPullup = false
    
    var tableview: UITableView?
    
    var refreshControl: SIRefreshControl?
    
    lazy var navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.cz_screenWidth(), height: 64))
    
    lazy var navItem = UINavigationItem()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        

        setupUI()
        
//        loadData()
        
        ///根据登录状态,判断是否继承加载数据方法
        SINetworkTools.shared.userLogon ? loadData() : ()
        
        NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess), name: NSNotification.Name(rawValue: userLoginSuccessedNotification), object: nil)
        
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override var title: String? {
        didSet {
            navItem.title = title
            
        }
    }
    
    func loadData() {
       
//        refreshControl?.endRefreshing()
        
    }
   
}

//MARK: - 登录界面登录成功
extension SIBaseViewController {
    
    @objc private func loginSuccess(n: Notification) {
        
        navItem.leftBarButtonItem = nil
        navItem.rightBarButtonItem = nil
        
        //FIXME: - 重要技巧 如果view设置为nil,那么会调用loadView方法,然后调用viewDidLoad方法
        view = nil
        
        //避免再次注册
        NotificationCenter.default.removeObserver(self)
    }
    
}

extension SIBaseViewController {
    
    @objc private func login() {
        
        print("用户登录")
        //MARK: 发送通知
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: userNeedLoginSinaNotification), object: nil)
    }
    
    @objc private func register() {
        
        print("用户注册")
    }
    
    
}

//MARK: - 设置界面
extension SIBaseViewController {
    private func setupUI() {
        
        view.backgroundColor = UIColor.cz_random()
        
        automaticallyAdjustsScrollViewInsets = false
        
        setupNavigation()
        
        SINetworkTools.shared.userLogon ? setupTableView() : setupVisitorView()
        
    }
    
    
    //MARK: 访客视图
    private func setupVisitorView() {
        
        let visitorView = SIVisitorView(frame: view.bounds)
        
        visitorView.backgroundColor = UIColor.cz_color(withHex: 0xEDEDED)
        
        view.insertSubview(visitorView, belowSubview: navigationBar)
        
        visitorView.visitorInfo = visitorInfoDictonary
        
        visitorView.loginButton.addTarget(self, action: #selector(login), for: .touchUpInside)
        visitorView.registerButton.addTarget(self, action: #selector(register), for: .touchUpInside)
        
        navItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: .plain, target: self, action: #selector(register))
        navItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: .plain, target: self, action: #selector(login))
        
        
        
    }
    
    ///表格视图的建立
    func setupTableView() {
        tableview = UITableView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height), style: .plain)
        
        //        view.addSubview(tableview!)
        view.insertSubview(tableview!, belowSubview: navigationBar)
        
        tableview?.dataSource = self
        tableview?.delegate = self
        
        tableview?.contentInset = UIEdgeInsets(top: navigationBar.bounds.height, left: 0, bottom: tabBarController?.tabBar.bounds.height ?? 49, right: 0)
        
        tableview?.scrollIndicatorInsets = tableview!.contentInset
        
        refreshControl = SIRefreshControl()
        
        tableview?.addSubview(refreshControl!)
        
        refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged)
        
    }
    
    func setupNavigation() {
        
        view.addSubview(navigationBar)
        
        navigationBar.items = [navItem]
        
        navigationBar.barTintColor = UIColor.cz_color(withHex: 0xF6F6F6)
        
        //MARK: -下划线添加失败
        navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.darkGray(), NSUnderlineStyleAttributeName: "styleSingle"]
        
        navigationBar.tintColor = UIColor.orange()
    }
}

extension SIBaseViewController: UITableViewDataSource, UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return 10
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let row = indexPath.row
        
        let section = tableView.numberOfSections - 1
        
        if row < 0 || section < 0{
            
            return
        }
        
        let count = tableView.numberOfRows(inSection: section)
        
        if row == (count - 1) && !isPullup {
            
            print("上拉刷新")
            
            isPullup = true
            
            loadData()
        }
    }
}
